package com.yanqu.road.dao.impl.cross;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossGroupWeekRankDaoImpl extends TempDao {


    public Map<Integer, Map<Integer, Map<Integer, Map<Integer, LinkedList<CrossUserRank>>>>> getCrossGroupWeekRankListMap(int beginWeek, int endWeek) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_c_group_week_rank where weekId >= ? and weekId <= ?";
        Map<Integer, Map<Integer, Map<Integer, Map<Integer, LinkedList<CrossUserRank>>>>> dataMap = new ConcurrentHashMap<>();
        try {
            int i = 1;
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(i++, beginWeek);
            call.setInt(i++, endWeek);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUserRank data = initGroupWeekRank(rs);
                int groupId = rs.getInt("groupId");
                int weekId = rs.getInt("weekId");
                if (!dataMap.containsKey(groupId)) {
                    dataMap.put(groupId, new ConcurrentHashMap<>());
                }
                if (!dataMap.get(groupId).containsKey(weekId)){
                    dataMap.get(groupId).put(weekId, new ConcurrentHashMap<>());
                }
                if (!dataMap.get(groupId).get(weekId).containsKey(data.getBigRankType())){
                    dataMap.get(groupId).get(weekId).put(data.getBigRankType(), new ConcurrentHashMap<>());
                }
                if (!dataMap.get(groupId).get(weekId).get(data.getBigRankType()).containsKey(data.getType())){
                    dataMap.get(groupId).get(weekId).get(data.getBigRankType()).put(data.getType(), new LinkedList<>());
                }
                dataMap.get(groupId).get(weekId).get(data.getBigRankType()).get(data.getType()).addLast(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    private CrossUserRank initGroupWeekRank(ResultSet rs) throws SQLException {
        CrossUserRank data = new CrossUserRank();
        data.setBigRankType(rs.getInt("bigRankType"));
        String value = rs.getString("value");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        value = rs.getString("userBaseInfo");
        if(null == value){
            value = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(value, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo){
            data.setUserBaseInfo(userBaseInfo);
        }
        data.setUserId(rs.getLong("userId"));
        data.setParam(rs.getString("param"));
        data.setType(rs.getInt("type"));
        data.setRank(rs.getInt("rank"));
        data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
        return data;
    }

    public boolean updateCrossGroupWeekRankList(LinkedList<CrossUserRank> newRankList, int groupId, int weekId) {
        String sql = "REPLACE INTO t_c_group_week_rank(groupId, weekId, serverId, bigRankType, type, rank, userId, userBaseInfo, value, lastUpdateTime, param) "+
                " VALUES(?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            int rank = 1;
            for (CrossUserRank userRank : newRankList) {
                int i = 1;
                Map<Integer, DbParameter> para = new HashMap<>();
                para.put(i++, new DbParameter(Types.INTEGER, groupId));
                para.put(i++, new DbParameter(Types.INTEGER, weekId));
                para.put(i++, new DbParameter(Types.BIGINT, userRank.getUserBaseInfo().getServerId()));
                para.put(i++, new DbParameter(Types.INTEGER, userRank.getBigRankType()));
                para.put(i++, new DbParameter(Types.INTEGER, userRank.getType()));
                para.put(i++, new DbParameter(Types.INTEGER, rank));
                para.put(i++, new DbParameter(Types.BIGINT, userRank.getUserId()));
                para.put(i++, new DbParameter(Types.NVARCHAR, userRank.getUserBaseInfoJsonStr()));
                para.put(i++, new DbParameter(Types.VARCHAR, userRank.getValue().toString()));
                para.put(i++, new DbParameter(Types.BIGINT, userRank.getLastUpdateTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, userRank.getParam()));
                mapList.add(para);
                rank++;
            }
            if (getDb().executeBatchQuery(sql, mapList) > -1) {
                return true;
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }
}
